/**
 * Copyright (C) 2015 RederXu
 *	本程序不保证完全正确，由于引用本程序导致的一切损失本人概不负责。
 *	有任何请疑问邮件至xujianflying@sohu.com
 */
package com.rederxu.request;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
 * 网络请求方法<br/>
 * 1.当前每个请求一个线程，执行完成后线程会指定释放，有时间了或将其改为线程池<br/>
 * 2.TIME_OUT = 20000 <br/>
 * 3.静态的handler最好在UI线程中第一次调用，否则会导致非UI线程调用UI控件的错误<br/>
 * 4.线程池，最多支持10个并发，更多的需要排队<br/>
 * @author RederXu
 * @date 2015-9-17 
 * */
public class HTTPRequest {

	private final static int TIME_OUT = 20000;
	private final static String TAG = "HTTPRequest";
	private final static int CODE_INIT_HANDLER = 100;
	private final static int CODE_REQUEST_OVER = 101;
	private final static int CODE_FILE_DOWNLOADING_OVER = 102;
	private final static int CODE_FILE_DOWNLOADING = 103;
	//线程池，最多10个并发
	private static ExecutorService threadPool = Executors.newFixedThreadPool(10); 
	
	//默认的加载菊花
	private static ProgressDialog progressDialog;
	/**
	 * 通用GET请求，示例如下
	 * 
	 * <code>
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;//参数，使用Bundle传入，也可以直接拼装url,只能传入String类型，否则参数为null
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;Bundle bundle = new Bundle();
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;bundle.putString("param1", "value1");
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;bundle.putString("param2", "value2");
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;//url，如果传参，url应该以文件结尾，视具体情况而定
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;String url = "http://www.baidu.com/index.html";
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;//发起请求
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;HTTPRequest.GET(url, bundle, new onRequestOverListener() {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;@Override
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;public void onRequestOver(String result) {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//打印返回结果，回到了UI线程
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Log.e("onRequestOver", result);
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	}
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;});
		</code>
	 * 
	 * */
	public static void GET(final Context context,final String url_,final Bundle bundle,
			final onRequestOverListener listener) {
		handler.sendEmptyMessage(CODE_INIT_HANDLER);
		initPorgressDialog(context);
		threadPool.execute(new Runnable(){
			@Override
			public void run() {
				try {
					String url = url_;
					String strResult = "";
					if (bundle != null) {
						url += "?";
						Set<String> keySet = bundle.keySet();
						for (String key : keySet) {
							String value = bundle.get(key) + "";
							url += key + "=" + value + "&";
						}
						url = url.substring(0, url.length() - 1);
					}
					Log.d("GetUrl", url);
					HttpGet httpGet = new HttpGet(url);
					CookieStore.setCookie(context, httpGet);
					HttpClient httpClient = new DefaultHttpClient();
					HttpResponse httpResponse = null;
					if(url_.startsWith("https")){
						httpClient = initHttpClient(httpClient.getParams());
						httpResponse = httpClient.execute(httpGet);
					}else{
						httpClient.getParams().setIntParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
						httpResponse = httpClient.execute(httpGet);
					}
					if (httpResponse.getStatusLine().getStatusCode() != 200) {
						Log.e(TAG,"StatusCode:" + httpResponse.getStatusLine());
						JSONObject jo = new JSONObject();
						jo.put("status", "GET错误");
						jo.put("message", httpResponse.getStatusLine());
						strResult = jo.toString();
					    sendMessage(listener,strResult);
						return;
					}
					try{
						List<Cookie> cookies = ((DefaultHttpClient) httpClient).getCookieStore().getCookies();
						CookieStore.saveCookie(cookies,context,url_);
					}catch(Exception e){
						Log.w("提取cookie错误", e.toString());
						e.printStackTrace();
					}
					strResult = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
				    sendMessage(listener,strResult);
				} catch (Exception e) {
					Log.e(TAG, e.toString());
				}
			}
		});
	}


	/***
	 * @author RederXu
	 * @date 2015-9-17
	 * 通用POST请求，示例如下
	 * 
	 * <code>
	 * 
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;//与GET几乎完全一样，只需调用HTTPRequest时改GET为POST即可
		
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;//参数，使用Bundle传入，也可以直接拼装url,只能传入String类型，否则参数为null
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;Bundle bundle = new Bundle();
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;bundle.putString("param1", "value1");
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;bundle.putString("param2", "value2");
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;//url，如果传参，url应该以文件结尾，视具体情况而定
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;String url = "http://www.baidu.com/index.html";
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;//发起请求
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;HTTPRequest.POST(url, bundle, new onRequestOverListener() {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	@Override
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	public void onRequestOver(String result) {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		//打印返回结果，回到了UI线程
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		Log.e("onRequestOver", result);
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	}
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;});
	 * </code>
	 * 
	 * */
	public static void POST(final Context context,final String url_,final Bundle bundle,
			final onRequestOverListener listener) {
		handler.sendEmptyMessage(CODE_INIT_HANDLER);
		initPorgressDialog(context);
		threadPool.execute(new Runnable(){

			@Override
			public void run() {
				try {
					String strResult = "";
					String url = url_;
					HttpPost httpPost = new HttpPost(url);
					Log.d("PostUrl", url);
					HttpClient httpClient = new DefaultHttpClient();
					
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					Set<String> keySet = bundle.keySet();
					for (String key : keySet) {
						String value = bundle.get(key) + "";
						Log.d("Post Params", key + "=" + value);
						params.add(new BasicNameValuePair(key, value));
					}
					UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,HTTP.UTF_8);
					httpPost.setEntity(entity);
					httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
					CookieStore.setCookie(context, httpPost);
					HttpResponse httpResponse = null;
					if(url_.startsWith("https")){
						httpClient = initHttpClient(httpClient.getParams());
						httpClient.getParams().setIntParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
						httpResponse = httpClient.execute(httpPost);
					}else{
						httpClient.getParams().setIntParameter(
								CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
						httpResponse = httpClient.execute(httpPost);
					}
					if (httpResponse.getStatusLine().getStatusCode() != 200) {
						JSONObject jo = new JSONObject();
						jo.put("status", "post请求错误");
						jo.put("message", httpResponse.getStatusLine());
						strResult = jo.toString();
					    sendMessage(listener,strResult);
						return;
					}
					try{
						List<Cookie> cookies = ((DefaultHttpClient)httpClient).getCookieStore().getCookies();
						CookieStore.saveCookie(cookies,context,url_);
					}catch(Exception e){
						Log.w("提取cookie错误", e.toString());
					}
					strResult = EntityUtils.toString(httpResponse.getEntity(),
							"UTF-8");
				    sendMessage(listener,strResult);
				} catch (Exception e) {
					String error = e.getMessage();
					if (error != null && error.contains("timed out")) {
						JSONObject jo = new JSONObject();
						try {
							jo.put("status", false);
							jo.put("message", "网络连接超时");
						    sendMessage(listener,jo.toString());
						} catch (JSONException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						Log.e(TAG, error);
					}
				}
			}
		});
	}
	
	/**
	 * 
	 * @param fileUrl,文件网络地址
	 * @param path,文件保存路径
	 * @param isCoverlap，当文件存在时是否覆盖
	 * @param 下载监听
	 * 文件下载，代码示例
	 
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String url = "http://192.168.1.174:8020/android/upload/HelloJNI.apk";
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String path = "/mnt/sdcard/";
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;HTTPRequest.fileDownload(url, path, false, new onFileDownloadListener() {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;	
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	@Override
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	public void onDownloading(int max, int progress) {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		// TODO Auto-generated method stub
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		Log.e("下载进度", progress + "/" + max);
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	}
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;	
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	@Override
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	public void onDownloadOver(String result) {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		Log.e("下载完成", result);
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;		
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	}
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;});
	 * */
	public static void fileDownload(final String fileUrl, final String path,final boolean isCoverlap,
			final onFileDownloadListener listener) {
		handler.sendEmptyMessage(CODE_INIT_HANDLER);
		threadPool.execute(new Runnable(){
			@Override
			public void run() {
				try{
					File f = new File(fileUrl);
					String filePath = path + f.getName();
					File file = new File(filePath);
					if(!file.exists()){
						file.createNewFile();
					}else{
						sendMessageFileDownloadOver(listener,filePath);
						return;
					}
					URL url = new URL(fileUrl);
					URLConnection con = url.openConnection();
					InputStream is = con.getInputStream();
					byte[] bs = new byte[1024];
					int len;
					int max = con.getContentLength();
					int progress = 0;
					OutputStream os = new FileOutputStream(filePath);
					while ((len = is.read(bs)) != -1) {
						os.write(bs, 0, len);
						progress += len;
						sendMessageFileDownloading(listener, max, progress);
					}
					os.close();
					is.close();
					sendMessageFileDownloadOver(listener,filePath);
				}catch(Exception e){
					Log.e("fileDownload", e.toString());
				}
			}
		});
	}
	
	public static void uploadFile(final Context context,final String uploadUrl,final String filePath,final onRequestOverListener listener){
		initPorgressDialog(context);
		handler.sendEmptyMessage(CODE_INIT_HANDLER);
		File file = new File(filePath);
		if (!file.exists()) {
			Log.e(TAG, "文件不存在");
			return;
		}
		threadPool.execute(new Runnable() {
			@Override
			public void run() {
				String end = "\r\n";
				String twoHyphens = "--";
				String boundary = "******";
				try {
					URL url = new URL(uploadUrl);
					HttpURLConnection httpURLConnection = (HttpURLConnection) url
							.openConnection();
					httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
					httpURLConnection.setDoInput(true);
					httpURLConnection.setDoOutput(true);
					httpURLConnection.setUseCaches(false);
					httpURLConnection.setRequestMethod("POST");
					httpURLConnection.setRequestProperty("Connection",
							"Keep-Alive");
					httpURLConnection.setRequestProperty("Charset", "UTF-8");
					httpURLConnection.setRequestProperty("Content-Type",
							"multipart/form-data;boundary=" + boundary);
					CookieStore.setCookie(context, httpURLConnection);
					DataOutputStream dos = new DataOutputStream(
							httpURLConnection.getOutputStream());
					dos.writeBytes(twoHyphens + boundary + end);
					dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
							+ filePath.substring(filePath.lastIndexOf("/") + 1)
							+ "\"" + end);
					dos.writeBytes(end);

					FileInputStream fis = new FileInputStream(filePath);
					byte[] buffer = new byte[8192]; // 8k
					int count = 0;
					while ((count = fis.read(buffer)) != -1) {
						dos.write(buffer, 0, count);
					}
					fis.close();

					dos.writeBytes(end);
					dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
					dos.flush();

					InputStream is = httpURLConnection.getInputStream();
					InputStreamReader isr = new InputStreamReader(is, "utf-8");
					BufferedReader br = new BufferedReader(isr);
					String result = br.readLine();
					sendMessage(listener, result);
					dos.close();
					is.close();

				} catch (Exception e) {
					e.printStackTrace();
					sendMessage(listener, "【Farmer】图片上传失败:" + e.toString());
				}
			}

		});
	}
	
	/***
	 *  文件上传，示例代码如下
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;String uploadUrl = "http://192.168.1.174:8020/android/FileUpload.php";
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;String filePath = "/mnt/sdcard/screenshot.png";
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;HTTPRequest.uploadFile(uploadUrl, filePath, new onRequestOverListener() {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	@Override
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	public void onRequestOver(String result) {
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;		Log.e("upload", result);
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;	}
		<br/>&nbsp;&nbsp;&nbsp;&nbsp;});
	 * */
	  public static void uploadFile(final String uploadUrl,final String filePath,final onRequestOverListener listener)
	  {
		  handler.sendEmptyMessage(CODE_INIT_HANDLER);
		  File file = new File(filePath);
		  if(!file.exists()){
			  Log.e(TAG, "文件不存在");
			  return;
		  }
		  threadPool.execute(new Runnable(){
			@Override
			public void run() {
				String end = "\r\n";
			    String twoHyphens = "--";
			    String boundary = "******";
			    try
			    {
			      URL url = new URL(uploadUrl);
			      HttpURLConnection httpURLConnection = (HttpURLConnection) url
			          .openConnection();
			      httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
			      httpURLConnection.setDoInput(true);
			      httpURLConnection.setDoOutput(true);
			      httpURLConnection.setUseCaches(false);
			      httpURLConnection.setRequestMethod("POST");
			      httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			      httpURLConnection.setRequestProperty("Charset", "UTF-8");
			      httpURLConnection.setRequestProperty("Content-Type",
			          "multipart/form-data;boundary=" + boundary);
			      //设置Cookie
			      try{
				      Context context = progressDialog.getContext();
				      CookieStore.setCookie(context, httpURLConnection);
			      }catch(Exception e){
			    	  Log.w(TAG, e.toString());
			      }
			      DataOutputStream dos = new DataOutputStream(
			          httpURLConnection.getOutputStream());
			      dos.writeBytes(twoHyphens + boundary + end);
			      dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
			          + filePath.substring(filePath.lastIndexOf("/") + 1)
			          + "\""
			          + end);
			      dos.writeBytes(end);
			 
			      FileInputStream fis = new FileInputStream(filePath);
			      byte[] buffer = new byte[8192]; // 8k
			      int count = 0;
			      // 锟斤拷取锟侥硷拷
			      while ((count = fis.read(buffer)) != -1)
			      {
			        dos.write(buffer, 0, count);
			      }
			      fis.close();
			 
			      dos.writeBytes(end);
			      dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			      dos.flush();
			 
			      InputStream is = httpURLConnection.getInputStream();
			      InputStreamReader isr = new InputStreamReader(is, "utf-8");
			      BufferedReader br = new BufferedReader(isr);
			      String result = br.readLine();
			      sendMessage(listener,result);
			      dos.close();
			      is.close();
			 
			    } catch (Exception e)
			    {
			      e.printStackTrace();
			      sendMessage(listener,"【Farmer】图片上传失败:" + e.toString());
			    }
			}
			  
		  });
	  }
	  
	  /**
	   * 清空本地cookie数据
	   * */
	  public static void clearCookie(Context context){
		  CookieStore.clear(context);
	  }
	  
	  private static Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			
			if(msg.what != CODE_INIT_HANDLER && progressDialog != null && progressDialog.isShowing()){
				try{
					progressDialog.dismiss();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
			switch(msg.what){
			case CODE_INIT_HANDLER:
				//初始化handler，使之始终处于UI线程中
				break;
			case CODE_REQUEST_OVER:
				onRequestOverListener listener = (onRequestOverListener)msg.obj;
				if(listener != null){
					listener.onRequestOver(msg.getData().getString("result"));
				}
				break;
			case CODE_FILE_DOWNLOADING:
				onFileDownloadListener lDownloading = (onFileDownloadListener)msg.obj;
				if(lDownloading != null){
					Bundle bundle = msg.getData();
					lDownloading.onDownloading(bundle.getInt("max"), bundle.getInt("progress"));
				}
				break;
			case CODE_FILE_DOWNLOADING_OVER:
				onFileDownloadListener lDownloadOver = (onFileDownloadListener)msg.obj;
				if(lDownloadOver != null){
					Bundle bundle = msg.getData();
					lDownloadOver.onDownloadOver(bundle.getString("result"));
				}
				break;
			}
			super.handleMessage(msg);
		}
	  };
	  
	  private static void sendMessage(onRequestOverListener listener,String result){
		    Bundle bundle = new Bundle();
		    bundle.putString("result", result);
		    Message msg = new Message();
		    msg.what = CODE_REQUEST_OVER;
		    msg.obj = listener;
		    msg.setData(bundle);
		    handler.sendMessage(msg);
	  }
	  
	  private static void sendMessageFileDownloadOver(onFileDownloadListener listener,String result){
		    Bundle bundle = new Bundle();
		    bundle.putString("result", result);
		    Message msg = new Message();
		    msg.what = CODE_FILE_DOWNLOADING_OVER;
		    msg.obj = listener;
		    msg.setData(bundle);
		    handler.sendMessage(msg);
	  }
	  
	  private static void sendMessageFileDownloading(onFileDownloadListener listener,int max,int progress){
		    Bundle bundle = new Bundle();
		    bundle.putInt("max", max);
		    bundle.putInt("progress", progress);
		    Message msg = new Message();
		    msg.what = CODE_FILE_DOWNLOADING;
		    msg.obj = listener;
		    msg.setData(bundle);
		    handler.sendMessage(msg);
	  }
	  
	  private static void initPorgressDialog(Context context){
		  if(HTTPRequest.Config.isLoadingEnable && HTTPRequest.Config.loadingBarViewId != -1){
				if(progressDialog != null && progressDialog.isShowing()){
					progressDialog.dismiss();
				}
				progressDialog = new ProgressDialog(context);
				progressDialog.setCancelable(true);
				progressDialog.show();
				progressDialog.setContentView(Config.loadingBarViewId);
			}
	  }
	  
	  public static class Config{
		  /**
		   * 是否显示默认的ProgressDialog
		   * */
		  public static boolean isLoadingEnable = false;
		  
		  /**
		   * 菊花View的ID
		   * */
		  public static int loadingBarViewId = -1;
	  }
	  
    private static HttpClient client = null;
    /**
     * 初始化HttpClient对象
     * @param params
     * @return
     */
	public static synchronized HttpClient initHttpClient(HttpParams params) {
		if (client == null) {
			try {
				KeyStore trustStore = KeyStore.getInstance(KeyStore
						.getDefaultType());
				trustStore.load(null, null);

				SSLSocketFactory sf = new SSLSocketFactoryImp(trustStore);
				// 允许所有主机的验证
				sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

				HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
				HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
				// 设置http和https支持
				SchemeRegistry registry = new SchemeRegistry();
				registry.register(new Scheme("http", PlainSocketFactory
						.getSocketFactory(), 80));
				registry.register(new Scheme("https", sf, 443));

				ClientConnectionManager ccm = new ThreadSafeClientConnManager(
						params, registry);

				return new DefaultHttpClient(ccm, params);
			} catch (Exception e) {
				e.printStackTrace();
				return new DefaultHttpClient(params);
			}
		}
		return client;
	}
	  
	  /**
	   * HTTPS请求的SSL处理
	   * */
	public static class SSLSocketFactoryImp extends SSLSocketFactory {
		final SSLContext sslContext = SSLContext.getInstance("TLS");

		public SSLSocketFactoryImp(KeyStore truststore)
				throws NoSuchAlgorithmException, KeyManagementException,
				KeyStoreException, UnrecoverableKeyException {
			super(truststore);

			TrustManager tm = new X509TrustManager() {
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				@Override
				public void checkClientTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException {
				}

				@Override
				public void checkServerTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException {
				}
			};
			sslContext.init(null, new TrustManager[] { tm }, null);
		}

		@Override
		public Socket createSocket(Socket socket, String host, int port,
				boolean autoClose) throws IOException, UnknownHostException {
			return sslContext.getSocketFactory().createSocket(socket, host,
					port, autoClose);
		}

		@Override
		public Socket createSocket() throws IOException {
			return sslContext.getSocketFactory().createSocket();
		}
	}
}
